package com.utils.module;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hechao on 2017/9/7.
 */
public class DeviceInfoUtils {

    //---------------------------------OPPO所需字段---------------------------------

    public static String getOsVersion(String name) {
        String line = null;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + name);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return line;
    }

    /**
     * 获取运营商名
     * @param mContext
     * @return
     */
    public static String getCarrieroperator(Context mContext) {

        TelephonyManager telManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);

        String operator = telManager.getNetworkOperatorName();

        return operator;

    }

    /**
     * 系统版本号
     * @return
     */
    public static String getOsVersionOppo(Context mContext){
        return SystemPropertiesProxy.get(mContext, "ro.build.version.opporom");
    }

    /**
     * 源码控制版本号
     * @return
     */
    public static String getIncreMental(){
        return android.os.Build.VERSION.INCREMENTAL ;
    }

    //---------------------------------OPPO所需字段---------------------------------

    //---------------------------------共有逻辑---------------------------------

    /**
     * 获取当前系统版本号
     * 6.0.1
     * @return
     */
    public static String getDeviceRelease(){
        return Build.VERSION.RELEASE;
    }

    public static String getPhoneNum(Context mContext) {
        TelephonyManager tm = (TelephonyManager) mContext.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        String deviceid = tm.getDeviceId();
        String tel = tm.getLine1Number();
        return tel ;
    }

    public static String getImei(Context mContext){
        TelephonyManager telephonyManager = (TelephonyManager) mContext.getApplicationContext().getSystemService(mContext.TELEPHONY_SERVICE);
        String imei = telephonyManager.getDeviceId();
        return imei ;
    }

    /**
     * 获取SDK版本
     * 23
     * @return
     */
    public static String getSDK_INT(){
        return Build.VERSION.SDK_INT+"";
    }

    //---------------------------------共有逻辑---------------------------------

    public static String getDeviceId(Context mContext) {
        String deviceId = ((TelephonyManager) mContext.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        return deviceId;
    }

    public static String getProductProcessor(String paramString1, String paramString2) {
        //获取 主频大小 "ro.product.processor", "unknown"
        //获取 内存大小 "ro.product.ram", "unknown"
        try {
            return (String) Class.forName("android.os.SystemProperties").getDeclaredMethod("get", new Class[]{String.class, String.class}).invoke(null, new Object[]{paramString1, paramString2});
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getAndroidId(Context mContext) {
        return android.provider.Settings.Secure.getString(mContext.getApplicationContext().getContentResolver(), "android_id");
    }

    /**
     * 像素密度
     *
     * @return
     */
    public static String getDeviceDensityDpi(Context mContext) {
        DisplayMetrics lDisMet = mContext.getApplicationContext().getResources().getDisplayMetrics();
        return lDisMet.densityDpi + "";
    }

    /**
     * 手机品牌
     *
     * @return
     */
    public static String getDeviceBrand() {
        return Build.BRAND;
    }

    /**
     * 屏幕宽度
     *
     * @param mContext
     * @return
     */
    public static String getScreenWidth(Context mContext) {

        DisplayMetrics localDisplayMetrics = new DisplayMetrics();
        ((WindowManager) mContext.getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(localDisplayMetrics);
        return localDisplayMetrics.widthPixels + "";
    }

    /**
     * 屏幕高度
     *
     * @param mContext
     * @return
     */
    public static String getScreenHeight(Context mContext) {
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();
        ((WindowManager) mContext.getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(localDisplayMetrics);
        return localDisplayMetrics.heightPixels + "";
    }

    /**
     * Y密度
     *
     * @param mContext
     * @return
     */
    public static String getYPmDensity(Context mContext) {
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();
        ((WindowManager) mContext.getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(localDisplayMetrics);
        return localDisplayMetrics.ydpi + "";
    }

    /**
     * X密度
     *
     * @param mContext
     * @return
     */
    public static String getXPmDensity(Context mContext) {
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();
        ((WindowManager) mContext.getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(localDisplayMetrics);
        return localDisplayMetrics.xdpi + "";
    }


    public static String getDeviceSerial() {
        return Build.SERIAL;
    }

    /**
     * 获取手机 Model
     * Build.MODEL====== MI+5
     *
     * @return
     */
    public static String getDeviceModel() {
        return Build.MODEL;
    }

    /**
     * cpu处理器
     *
     * @return
     *
     *
    ic static String n(Context paramContext) {
    FileReader fr;
    try {
    fr = new FileReader("/proc/cpuinfo");
    BufferedReader br = new BufferedReader(fr);
    String line = null;
    while ((line = br.readLine()) != null) {
    line = line.toLowerCase();
    System.out.println("/proc/cpuinfo===="+line);
    if (line.contains("hardware")) {
    String[] strs = line.split(":");
    if (strs.length >= 2) {
    String str1 = strs[1].toLowerCase().trim();
    if (b(paramContext, str1)) {
    str1 = a(paramContext, str1);
    if (br != null)
    br.close();
    return str1;
    }
    if (br != null)
    br.close();
    return str1;
    }
    }
    }
    if (br != null)
    br.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return "";
    }
     *
     */
    public static String getCupInfo(Context mContext) {
        FileReader fr;
        try {
            fr = new FileReader("/proc/cpuinfo");
            BufferedReader br = new BufferedReader(fr);
            String line = null;
            while ((line = br.readLine()) != null) {
                line = line.toLowerCase();
                if (line.contains("hardware")) {
                    String[] strs = line.split(":");
                    if (strs.length >= 2) {
                        String str1 = strs[1].toLowerCase().trim();
                        if (b(mContext.getApplicationContext())) {
                            str1 = a(mContext.getApplicationContext(), str1);
                            if (br != null)
                                br.close();
                            return str1;
                        }
                        if (br != null)
                            br.close();
                        return str1;
                    }
                }
            }
            if (br != null)
                br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String a(Context paramContext, String paramString) {
        if ("true".equals(a("ro.mediatek.gemini_support", "true")))
            return paramString;
        return "null";
    }

    public static String a(String paramString1, String paramString2) {
        String str = paramString2;
        try {
            str = (String) Class.forName("android.os.SystemProperties").getDeclaredMethod("get", new Class[]{String.class, String.class}).invoke(null, new Object[]{paramString1, paramString2});
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return str;
    }

    public static boolean b(Context paramContext) {
        TelephonyManager tm = (TelephonyManager) paramContext.getSystemService(Context.TELEPHONY_SERVICE);
        try {
            Method method = tm.getClass().getDeclaredMethod("listenGemini", new Class[]{PhoneStateListener.class, Integer.TYPE, Integer.TYPE});
            Method method2 = tm.getClass().getDeclaredMethod("getDeviceIdGemini", new Class[]{Integer.TYPE});
            if ((method != null) && (method2 != null))
                return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * ARM指令文件
     * arm64-v8a
     *
     * @return
     */
    public static String getArm() {
        return Build.CPU_ABI;
    }

    public static String getArm2() {
        return Build.CPU_ABI2;
    }

    /**
     * CUPINFO [0] [1] [2] [3]
     * @return
     */
    public static String getCupInfo() {
        String[] cpuInfo = new String[4];
        try {
            StringBuffer sb = new StringBuffer();
            sb.append("abi: ").append(Build.CPU_ABI).append("n");
            if (new File("/proc/cpuinfo").exists()) {
                try {
                    BufferedReader br = new BufferedReader(new FileReader(new File("/proc/cpuinfo")));
                    String aLine;
                    while ((aLine = br.readLine()) != null) {
                        String[] lStrArray = new String[3];
                        lStrArray[0] = "Processor\\s*:\\s*(.*)";
                        lStrArray[1] = "CPU\\s*variant\\s*:\\s*0x(.*)";
                        lStrArray[2] = "Hardware\\s*:\\s*(.*)";
                        int i;
                        for (i = 0; i < 3; ++i) {
                            Pattern lpattern = Pattern.compile(lStrArray[i]);
                            Matcher lMatcher = lpattern.matcher(aLine);
                            if (lMatcher.find()) {
                                cpuInfo[i] = lMatcher.toMatchResult().group(1);
                            }
                        }
                    }
                    if (br != null) {
                        br.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Throwable t) {
        };

        String str4 = null;
        try {
            FileReader lfreader = new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq");
            try {
                char[] lchar = new char[1024];
                BufferedReader lbufferR = new BufferedReader(lfreader, 1024);
                while (true) {
                    int v5 = lbufferR.read(lchar, 0, 1024);
                    if (v5 == -1) {
                        break;
                    }
                    str4 = str4 + new String(lchar, 0, v5);
                }
                lbufferR.close();
                lfreader.close();
//                cpuInfo[3] = str4 + "\\ n";
                cpuInfo[3] = str4;
            } catch (Throwable t) {
            }
            ;
        } catch (Throwable t) {
        }
        return cpuInfo[0] + "  :  " + cpuInfo[1] + "  :  " + cpuInfo[2] + "  :  " + cpuInfo[3];
    }

    /**
     * 硬件制造厂商
     * Xiaomi
     * @return
     */
    public static String getManuFacture() {
        return Build.MANUFACTURER.trim();
    }

    public static String getProcMemInfo() {
        int[] v2 = new int[2];
        String mem = "";
        try {
            FileReader lFileR = new FileReader("/proc/meminfo");
            BufferedReader lBF = new BufferedReader(lFileR, 1024);
            int[] v3 = new int[4];
            int i;
            for (i = 0; i < 4; ++i) {

                v3[i] = Integer.valueOf(lBF.readLine()).intValue();
            }

            v2[0] = v3[0];
            v2[1] = v3[3] + v3[2] + v3[1];          //memoryInfo 1 2
            mem = v2[0] + "-&&-" + v2[1];
        } catch (Throwable t) {
        }
        return v2[0] + "," + v2[1];
    }

    /**
     * 获取磁盘空间
     * @return
     */
    public static String getDiskSpace(){
        int totalDiskSpace = 0;
        try {
            int[] totle = new int[2];
            StatFs lStat = new StatFs(Environment.getDataDirectory().getAbsolutePath());
            totle[0] = lStat.getBlockCount() * ((lStat.getBlockSize()) / 512) / 2;
            StatFs lStaF = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
            totle[1] = lStaF.getBlockCount() * ((lStaF.getBlockSize()) / 512) / 2;
            totalDiskSpace = totle[0] + totle[1];
        } catch (Throwable t) {
        }
        return totalDiskSpace + "" ;
    }

    /**
     * 获取时区标记
     * Asia/Shanghai
     * @return
     */
    public static String getZoneTime(){
        return TimeZone.getDefault().getID();
    }

    /**
     * 获取本地语言
     * zh_CN
     * @return
     */
    public static String getLocalLanguage(){
        return Locale.getDefault().toString();
    }

    /**
     * 无线电固件版本
     * TH20c1.9-00055
     * @return
     */
    public static String getBasebandVersion(){
        return Build.getRadioVersion();
    }

    /**
     * 设备的唯一标识。由设备的多个信息拼接合成
     * Xiaomi/gemini/gemini:6.0.1/MXB48T/V8.1.6.0.MAACNDI:user/release-keys
     * @return
     */
    public static String getDeviceFingerprint(){
        return Build.FINGERPRINT ;
    }

    /**
     * 获取时区相关
     * @return
     */
    public static String getTimeZoneV(){
        return Float.valueOf((((float) TimeZone.getDefault().getRawOffset())) / 3600000f)+"";
    }

    /**
     * 获取当前系统语言
     * zh
     * @return
     */
    public static String getLanguage(){
        return Locale.getDefault().getLanguage();
    }

    /**
     * CPU/BAI型号
     * arm64-v8a
     * @return
     */
    public static String getCupBai(){
        return Build.CPU_ABI ;
    }

    public static String getSerialNo(){
        String serialNo = "";
        try {
            Class class1 = Class.forName("android.os.SystemProperties");
            Method method = class1.getMethod("get",String.class);
            serialNo = (String)method.invoke(class1,"ro.serialno");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return serialNo;
    }

    public static String getPhoneImsi(Context mContext){
        TelephonyManager mTelephonyMgr = (TelephonyManager) mContext.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        return mTelephonyMgr.getSubscriberId();
    }

    public static String getBuildId(){
        return Build.ID;
    }

    public static String getVivoId(){
        FileReader fr;
        String line = "" ;
        try {
            fr = new FileReader("/sys/block/mmcblk0/device/cid");
            BufferedReader br = new BufferedReader(fr);
            line = br.readLine();
            //Processor	: AArch64 Processor rev 2 (aarch64)
            if (br != null)
                br.close();
            if ( StringUtils.isEmpty(line) ){
                fr = new FileReader("/sys/ufs/ufsid");
                BufferedReader br1 = new BufferedReader(fr);
                line = br1.readLine() + "";
            }
        } catch (Exception e) {
            try {
                if ( StringUtils.isEmpty(line) ){
                    fr = new FileReader("/sys/ufs/ufsid");
                    BufferedReader br1 = new BufferedReader(fr);
                    line = br1.readLine() + "";
                }
            }catch (Exception e1){

            }
        }
        return line;
    }

    public static String getIdVendor(){
        String line = "" ;
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("/sys/class/android_usb/android0/idVendor"))));
            line = reader.readLine();
        }catch (Exception e){

        }
        return line;
    }

    public static String getIdProduct(){
        String line = "" ;
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("/sys/class/android_usb/android0/idProduct"))));
            line = reader.readLine();
        }catch (Exception e){

        }
        return line;
    }

    public static String getVivoVersion() {
        String line = "" ;
        try {
            Class  localClass = Class.forName("android.os.SystemProperties");
            Object localObject1 = localClass.newInstance();
            Object localObject2 = localClass.getMethod("get", new Class[] { String.class,
                    String.class }).invoke(localObject1, new Object[] { "ro.build.netaccess.version", Build.DISPLAY});
            System.out.println("Vivo软件版本号 :"+localObject2);
            line = localObject2.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return line;
    }

}
